<?php

class QRCode
{
	public function __construct()
	{
		include "phpqrcode.php";
	}

	/**
	 *生成二维码,如需传入带logo的二维码,需传入logo,否则默认生成原始二维码
	 *@param $value 传入二维码内容
	 *@param $logo 传入logo图片 不传入默认为生成原始二维码
	 *@param $size 传入二维码的大小,默认为6,范围1-40
	 *@return 路径拼接图片名字
	 */
	public function imgToCode($value, $size=6, $logo=false)
	{
		if($logo === false) {
			$errorCorrectionLevel = 'L';//容错级别 
			$filename = $this->get_image_name();
			//生成二维码图片 
			QRcode::png($value, '../public/runtime/image/qrcode/'.$filename, $errorCorrectionLevel, $size, 2); 
		} else {
			$errorCorrectionLevel = 'L';//容错级别 
			$filename = $this->get_image_name();
			//生成二维码图片 
			QRcode::png($value, '../public/runtime/image/qrcode/'.$filename, $errorCorrectionLevel, $size, 2); 
			$QR = $filename;//已经生成的原始二维码图 保存在当前目录
		 
			if ($logo !== FALSE) { 
				$QR = imagecreatefromstring(file_get_contents('../public/runtime/image/qrcode/'.$QR)); 
				$logo = imagecreatefromstring(file_get_contents($logo)); 
				$QR_width = imagesx($QR);//二维码图片宽度 
				$QR_height = imagesy($QR);//二维码图片高度 
				$logo_width = imagesx($logo);//logo图片宽度 
				$logo_height = imagesy($logo);//logo图片高度 
				$logo_qr_width = $QR_width / 5; 
				$scale = $logo_width/$logo_qr_width; 
				$logo_qr_height = $logo_height/$scale; 
				$from_width = ($QR_width - $logo_qr_width) / 2; 
				 //重新组合图片并调整大小 
				imagecopyresampled($QR, $logo, $from_width, $from_width, 0, 0, $logo_qr_width, 
				$logo_qr_height, $logo_width, $logo_height); 
			} 
			//输出图片 
			// Header("Content-type: image/png");
			// ImagePng($QR);
			$filename = $this->get_image_name();
			imagepng($QR,'../public/runtime/image/qrcode'.$filename);
		}
		return '../public/runtime/image/qrcode/'.$filename;
	}

	public function get_image_name()
	{
		$randStr = null;
		$str = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
		$max = strlen($str) - 1;
		for($i = 0;$i < 5; $i++) {
			$randStr .= $str[rand(0, $max)];
		}
		$filename = time().$randStr;
		return md5($filename).".png";
	}
}